<?php

/**
 * @author liyi
 * @copyright 2018.12.10
 */

namespace Common\Controller;
use Think\Controller;
use think\Error;
use Think\Log;
use Org\Util\WXyjxcx;

// 公共接口
class ApiiController extends Controller {

    function __construct()
    {
        parent::__construct();
        //ini_set('display_errors', 1);
        //error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);  //屏蔽通知和警告
        //error_reporting(E_ALL);
    }

    /**
     * 微信登录 用户首次访问，调用微信接口获取openid和用户信息。将openid写入服务器端的cookie,将用户的信息写入redis缓存中，以openid作为redis的key。
     */
    public function wxAuthor($type,$code) {
        $data = C($type);
        $request = array(
            'appid' => $data['APPID'],
            'secret' => $data['APPSECRET'],
            'js_code' => $code,
            'grant_type' => 'authorization_code',
        );

        //获取sessionkey
        $wxxcx = new WXyjxcx();
        $res = $wxxcx->getOpenid($request);

        if($res['code'] != 200) {
            Log::write('微信受权失败！','NOTIC');
        }

        if ($res['code'] != 200 || !isset($res['result']) || !$res['result'])
        {
            $this->response(2, "登陆失败");
        }

        $result = json_decode($res['result'], true);
        $session_key = $result['session_key'];
        $openid = $result['openid'];
        if (!$openid)
        {
            Log::write('获取不到openid'.json_encode($res),'NOTIC');
            $this->response(2, "登陆失败,获取不到openid");
        }
        return $result;
    }


    public function wxAccessToken($type) {
        $data = C($type);
        $request = array(
            'appid' => $data['APPID'],
            'secret' => $data['APPSECRET'],
            'grant_type' => 'client_credential',
        );
        //获取accessToken
        $wxxcx = new WXyjxcx();
        $res = $wxxcx->getAccessToken($request);

        if ($res['code'] != 200 || !isset($res['result']) || !$res['result'])
        {
            $this->response(2, "微信获取AccessToken失败！",$res);
        }
        $result = json_decode($res['result'], true);

        return $result;
    }

    public function wxActivityId($access_token) {
        $request = array('access_token'=>$access_token);
        //获取createActivityId
        $wxxcx = new WXyjxcx();
        $res = $wxxcx->getCreateActivityId($request);
        if ($res['code'] != 200 || !isset($res['result']) || !$res['result'])
        {
            $this->response(2, "微信获取createActivityId失败！",$res);
        }
        $result = json_decode($res['result'], true);

        return $result;
    }

    public function wxMessageWxopen($access_token,$activity_id,$target_state) {
        $request = array('access_token'=>$access_token);

        //$a = "'activity_id'=>$activity_id,'target_state'=>$target_state";
        //获取createActivityId
        $wxxcx = new WXyjxcx();
        $res = $wxxcx->getMessageWxopen($request);
        if ($res['code'] != 200 || !isset($res['result']) || !$res['result'])
        {
            $this->response(2, "微信获取wxMessageWxopen失败！",$res);
        }
        $result = json_decode($res['result'], true);

        return $result;
    }

    public function msgSecCheck($access_token,$content) {
        $request = array(
            'access_token' => $access_token,
            'content' => $content
        );
        $wxxcx = new WXyjxcx();
        $res = $wxxcx->sendCheck($request);

        if ($res['code'] != 200 || !isset($res['result']) || !$res['result'])
        {
            $this->response(2, "微信内容验证失败！",$res);
        }

        $result = json_decode($res['result'], true);

        if( $result['errcode'] != 0 ) {
            $this->response(3, "微信内容验证失败！",$result);
        }

        return true;
    }

    public function isLogin($key) {
        $uid = session($key.'uid');
        if(empty($uid)) {
            return false;
        }
        return $uid;
    }

    public function isParamLogin($id) {
        if(empty($id)) {
            $this->response(1, "参数为空请先登录");
        }
        $map['id'] = $id;
        $ret = M('users')->field('id')->where($map)->find();
        if(empty($ret)) {
            $this->response(2, "用户不存在");
        }
        return $ret['id'];
    }

    /*
     * 签到记录
     * $uid 用户ID    $type 奖励类型  $row 一条或多条  $time 签到时间段
     */
    public function getRecord($uid,$type,$row='all',$time='') {
        //$map['uid'] = $this->uid;
        $map['uid'] = isset($this->uid)?$this->uid:$uid;
        $map['reward_type'] = $type;
        //$map['status'] = 1;

        if(!empty($time)) {
            $map['left(create_time,10)'] = $time;
        }
        if($row=='one') {
            $ret = M('users_draw_log')->where($map)->find();
        }else {
            $ret = M('users_draw_log')->where($map)->select();
        }
        //echo M('users_draw_log')->getLastSql();
        // if(empty($ret)) {
        //     $this->response(1,'操作失败');
        // }
        return $ret;
    }

    // 游戏复活
    public function revive($uid,$coin,$type)
    {
        $ruleType = array('1'=>'金币','2'=>'钻石','3'=>'复活币','4'=>'积分');
        $rule = array('1'=>'gold','2'=>'diamonds','3'=>'revive','4'=>'score');

        $content = $ruleType[$type];
        $param =  $rule[$type];

        $map['id'] = $uid;
        if(!$uid) {
            $this->response(2, "用户uid不能为空");
        }

        if(!$coin) {
            $this->response(3, $content."不能为空");
        }

        $ret = M('users')->where($map)->find();

        if(empty($ret)) {
            $this->response(4, "用户不存在");
        }

        if($ret[$param] < $coin) {
            $this->response(5, $content."不足");
        }

        $res = M('users')->where($map)->setDec($param,$coin);

        return $res;
    }

    // 奖励或处罚
    public function setGold($uid,$type,$proptype,$prop,$lazyTime=0)
    {

        $ruleType = array('1'=>'金币','2'=>'钻石','3'=>'奖券','4'=>'积分');
        $rule = array('1'=>'gold','2'=>'diamonds','3'=>'lottery','4'=>'score');

        $content = $ruleType[$proptype];

        $param =  $rule[$proptype];//diamonds

        if(empty($prop)) {
            $this->response(2,$content.'不能为空');
        }

        if(!in_array($type,array('inc','dec'))) {
            $this->response(3,'操作类型有误');
        }

        $map['id'] = $uid;
        $users = M('users')->where($map)->find();

        if($type == 'dec' && $users[$param] < $prop ) {
            $this->response(4,$content.'不足');
        }

        if($type == 'dec') {  // 减少

            $ret = M('users')->where($map)->setDec($param, $prop);

            if(empty($ret)) {
                Log::write('减少'.$content.'失败uid:'.$uid.'|操作类型：'.$type.'|操作道具：'.$content.'|操作值：'.$prop,'ERROR');
                $this->response(1, "操作失败");

            }
        }

        if($type == 'inc') {  // 增加
            $ret = M('users')->where($map)->setInc($param, $prop);
            if(empty($ret)) {
                Log::write('增加'.$content.'失败uid:'.$uid.'|操作类型：'.$type.'|操作道具：'.$content.'|操作值：'.$prop,'ERROR');
                $this->response(1, "操作失败");
            }
        }
        return $ret;
    }

    public function get_rand($proArr) {
        $result = '';

        //概率数组的总概率精度
        $proSum = array_sum($proArr);

        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);

        return $result;
    }


    public function countLog($key,$field,$dbId=0,$value=1) {
        $redis = REDIS('activity');
        $redis->select($dbId);
        $incr = $redis->hIncrBy($key,$field,$value);
        return $incr;
    }

    public function userCountLog($key,$field,$dbId=0) {
        $redis = REDIS('activity');
        $redis->select($dbId);
        $redis->sadd($key,$field);
        $number = $redis->scard($key);

        return $number;
    }

    public function sendMsge($contents)
    {
        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1);
        // 推送的数据，包含uid字段，表示是给这个uid推送

        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($contents)."\n");
        // 读取推送结果
        return fread($client, 8192);
    }


    public function getSession($key,$val) {

        session($key,$val); // 设置session_id
        $sessionId = session_id();
        return $sessionId;

    }


    public function commInviteRecord($uid,$invite_uid,$type=1,$time,$dbname,$cacheKey,$cacheval,$dbId=0)
    {
        if(empty($uid) || empty($invite_uid)) {
            $this->response(4, "邀请人与被邀请人不能为空");
        }
        // 无限钻石
        if($type == '99'){
            // 判断是否新老用户 老用户不能再次邀请 新用户每人只能被邀请一次
            $where['id'] = $uid;
            $where['type'] = 2;// 老用户标识
            $user_id = M('mining_game.users')->where($where)->find();
            if( !empty($user_id)){
                $this->response(2, "只能邀请一次");
            }else{
                // 如果是新用户 增加邀请表 更新老用户标识
                $w_user['id'] = $uid;
                $w_data['type'] = 2;  //老用户
                $w_data['update_time'] = date('Y-m-d H:i:s');
                $ret2 = M('mining_game.users')->where($w_user)->save($w_data);

                $data['uid'] = $uid;
                $data['invite_uid'] = $invite_uid;
                $data['create_time'] = date('Y-m-d H:i:s');
                $data['type'] = $type;
                $ret = M($dbname)->add($data);
                if(empty($ret) && empty($ret2)) {
                    $this->response(1, "操作失败");
                }else{
                    $this->response(0, "操作成功");
                }
            }
        }

        $time = !empty($time) ? $time : date('Y-m-d');

        if(empty($invite_uid)) {
            $this->response(2, "邀请人id不能为空");
        }
        $endTime = $time.' 23:59:59';

        $map['uid'] = $uid;// 被邀请人ID
        $map['invite_uid'] = $invite_uid;      // 发链接的邀请人
        $map['create_time']  = array('between',"$time,$endTime");
        $map['type'] = $type;
        $user = M($dbname)->where($map)->find();

        if (!empty($user))
        {
            $this->response(3, "已被邀请过");
        }

        if( $uid != $invite_uid ) {  //如果不是自己邀请自己

            $data['uid'] = $uid;
            $data['invite_uid'] = $invite_uid;
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['type'] = $type;
            $ret = M($dbname)->add($data);
            if(empty($ret)) {
                $this->response(1, "操作失败");
            }
            $incr = $this->countLog($cacheKey,$cacheval,$dbId);  // 邀请用户次数
            return $incr;
        }
        $this->response(0, "操作成功");
    }


    public function commUserInvite($uid,$type=1,$dbname,$dbname2,$time)
    {
        $strType = implode(',', $type);
        //$map['invite_uid'] = $uid;
        $map['invite_uid'] = $uid; // 被邀请人用户
        $map['type'] = is_array($type) ? array('in',$strType) : $type;
        if(!empty($time)){  //当天邀请记录
            $endTime = $time.' 23:59:59';
            $map['create_time']  = array('between',"$time,$endTime");
        }

        $list = M($dbname)->field('uid,type,create_time')->where($map)->select();

        $userInfo = array();
        $number = 0;
        if(!empty($list)) {
            $number = intval(count($list));
            $uidArr = array_column($list,'uid');
            $timeArr = array_column($list,'create_time','uid');
            $uidStr = implode(',', $uidArr);
            $where['id'] = array('in',$uidStr);

            $userInfo = M($dbname2)->field('id,nickname,avatar')->where($where)->select();
            if(!empty($userInfo)) {
                $nicknameArr = array_column($userInfo,'nickname','id');
                $avatarArr   = array_column($userInfo,'avatar','id');
            }
            foreach($list as $k=>$v) {
                $list[$k]['nickname'] = $nicknameArr[$v['uid']];
                $list[$k]['avatar'] = $avatarArr[$v['uid']];
                $list[$k]['create_time'] = strtotime($v['create_time']);
            }
        }

        $data = array('userInfo'=>$list,'number'=>$number);
        //$this->response(0,"ok",array('userInfo'=>$userInfo,'number'=>$number));
        return $data;
    }

    // 公共邀请类型(type 扩展)
    public function commInviteType($type,$uid,$invite_uid,$dbname){
        // 无限钻石
        if($type == '99'){
            // 判断是否新老用户 老用户不能再次邀请 新用户每人只能被邀请一次
            $where['invite_uid'] = $invite_uid;
            $where['type'] = 99;
            $user_id = M($dbname)->where($where)->find();
            if( !empty($user_id)){
                $this->response(2, "新用户只能邀请一次");
            }else{
                $data['uid'] = $uid;
                $data['invite_uid'] = $invite_uid;
                $data['create_time'] = date('Y-m-d H:i:s');
                $data['type'] = $type;
                $ret = M($dbname)->add($data);
                if(empty($ret)) {
                    $this->response(1, "操作失败");
                }else{
                    $this->response(0, "操作成功");
                }
            }
        }
        /////////////////////////////////////////////////////////////////
    }

    // 公共邀请记录
    public function commInviteRecord_api($uid,$invite_uid,$type=1,$time,$dbname,$dbname2,$cacheKey,$cacheval,$dbId=0)
    {
        if(empty($uid) || empty($invite_uid)) {
            $this->response(4, "邀请人与被邀请人不能为空");
        }

        $time = !empty($time) ? $time : date('Y-m-d');

        if(empty($invite_uid)) {
            $this->response(2, "邀请人id不能为空");
        }
        $this->commInviteType($type,$uid,$invite_uid,$dbname);  // 邀请类型接口

        $endTime = $time.' 23:59:59';
        $map['uid'] = $uid;// 发链接的邀请人
        $map['invite_uid'] = $invite_uid;// 被邀请人ID
        $map['create_time']  = array('between',"$time,$endTime");
        $map['type'] = $type;
        $user = M($dbname)->where($map)->find();

        if (!empty($user))
        {
            $this->response(3, "已被邀请过");
        }

        if( $uid != $invite_uid ) {  //如果不是自己邀请自己

            $data['uid'] = $uid;
            $data['invite_uid'] = $invite_uid;
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['type'] = $type;
            $ret = M($dbname)->add($data);
            if(empty($ret)) {
                $this->response(1, "操作失败");
            }
            $incr = $this->countLog($cacheKey,$cacheval,$dbId);  // 邀请用户次数
            $this->response(0, "操作成功");
        }else{
            $this->response(5, "不能自己邀请自己");
        }

    }

    // 公共邀请列表
    public function commUserInvite_api($uid,$type=1,$dbname,$dbname2,$time)
    {
        $strType = implode(',', $type);
        $map['uid'] = $uid; // 邀请人
        $map['type'] = is_array($type) ? array('in',$strType) : $type;
        if(!empty($time)){  //当天邀请记录
            $endTime = $time.' 23:59:59';
            $map['create_time']  = array('between',"$time,$endTime");
        }

        $list = M($dbname)->field('invite_uid,type,create_time')->where($map)->group('invite_uid')->select();

        $userInfo = array();
        $number = 0;
        if(!empty($list)) {
            $number = intval(count($list));
            $uidArr = array_column($list,'invite_uid');
            $timeArr = array_column($list,'create_time','invite_uid');
            $uidStr = implode(',', $uidArr);
            $where['id'] = array('in',$uidStr);

            $userInfo = M($dbname2)->field('id,nickname,avatar')->where($where)->select();
            if(!empty($userInfo)) {
                $nicknameArr = array_column($userInfo,'nickname','id');
                $avatarArr   = array_column($userInfo,'avatar','id');
            }
            foreach($list as $k=>$v) {
                $list[$k]['nickname'] = $nicknameArr[$v['invite_uid']];
                $list[$k]['avatar'] = $avatarArr[$v['invite_uid']];
                $list[$k]['create_time'] = strtotime($v['create_time']);
            }
        }

        $data = array('userInfo'=>$list,'number'=>$number);
        return $data;
    }

    // 炮王2 邀请列表
    public function commUserInvite_p2($uid,$type=1,$dbname,$dbname2,$time)
    {
        $strType = implode(',', $type);
        //$map['invite_uid'] = $uid;
        $map['userid'] = $uid; // 邀请人用openid
        $map['type'] = is_array($type) ? array('in',$strType) : $type;
        if(!empty($time)){  //当天邀请记录
            $endTime = $time.' 23:59:59';
            $map['create_time']  = array('between',"$time,$endTime");
        }

        $list = M($dbname)->field('userid,invited_userid,type,create_time')->where($map)->select();

        $userInfo = array();
        $number = 0;
        if(!empty($list)) {
            $number = intval(count($list));
            $uidArr = array_column($list,'invited_userid');
            $timeArr = array_column($list,'create_time','invited_userid');
            $uidStr = implode(',', $uidArr);
            $where['userid'] = array('in',$uidStr);

            $userInfo = M($dbname2)->field('userid,nickname,avatar')->where($where)->select();
            if(!empty($userInfo)) {
                $nicknameArr = array_column($userInfo,'nickname','userid');
                $avatarArr   = array_column($userInfo,'avatar','userid');
            }
            foreach($list as $k=>$v) {
                $list[$k]['nickname'] = $nicknameArr[$v['invited_userid']];
                $list[$k]['avatar'] = $avatarArr[$v['invited_userid']];
                $list[$k]['create_time'] = strtotime($v['create_time']);
            }
        }

        $data = array('userInfo'=>$list,'number'=>$number);
        //$this->response(0,"ok",array('userInfo'=>$userInfo,'number'=>$number));
        return $data;
    }

    // 邀请好友关联列表
    public function commUserInvites($id,$array_id,$uid,$dbname,$dbname2)
    {
        $map[$array_id['i_id']] = $uid; // 邀请人用户
        $map2[$array_id['uid']] = $uid; // 被邀请人用户

        $list = M($dbname)->field($array_id['uid'])->where($map)->group($array_id['uid'])->select();// 对应被邀请人
        $list2 = M($dbname)->field($array_id['i_id'])->where($map2)->group($array_id['i_id'])->select();// 对应邀请人
        $number = 0;
        $temp =  array();
        if(!empty($list) || !empty($list2)) {
            $number = intval(count($list)+count($list2));
            $uidArr = array_column($list,$array_id['uid']);
            $uidArr2 = array_column($list2,$array_id['i_id']);
            $uidArrs = array_merge($uidArr,$uidArr2);
            $uidStr = implode(',', $uidArrs);
            $where[$id] = array('in',$uidStr);
            $where['status'] = 2;// 面向授权用户

            if($array_id['uid']=='uid'){
                // 掘金小美女
                $userInfo = M($dbname2)->field('id as uid,nickname,avatar,update_time,gold,status')->where($where)->select();
            }else{
                // 炮王2
                $userInfo = M($dbname2)->field('id,nickname,avatar,update_time,gold')->where($where)->select();
            }

            foreach ( $userInfo as $k => $value){
                if(!empty($value['nickname'])){
                    $temp[] = $value;
                }
            }
        }
        if(!empty($temp)) {
            $data = array('userInfo'=>$temp,'number'=>$number);
        }else{
            $data = false;
        }
        return $data;
    }

    public function commCryptData($uid,$gameType,$type=1,$cacheKey,$sessionKey,$encryptedData,$iv,$cacheKey2,$cacheval)
    {
        $data = C($gameType);
        $appid = $data['APPID'];

        $pc = new \Org\Util\WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);

        $data = $data ? json_decode($data, true) : '';
        $openGId = isset($data['openGId']) ? $data['openGId'] : 0;

        $redis = REDIS('activity');
        $evening = date('Y-m-d 23:59:59'); //每日23点59分
        $userKey = sprintf($cacheKey,$uid,$type);  //用户主键分享到群
        $shareKey = $redis->get($userKey);
        if( $type == 2 && $shareKey == $openGId  ) {
            $this->response(2,'每局游戏同一群只能分享一次');
        }

        if( $type == 1 && $shareKey == $openGId  ) {
            $this->response(3,'每天同一群只能分享一次');
        }

        if ( $errCode == 0 ) {  // 解密成功

            $redis->set($userKey,$openGId);  // 标记
            $redis->exprieAt($userKey,strtotime(date('Y-m-d 23:59:59'))); // 每日23点59分过期

            $this->countLog($cacheKey2,$cacheval);  // 记录分享次数日志
            $result = $data ? json_decode($data, true) : '';
            $this->response(0, "成功解密",$result);
        }

        $this->response(0, "解密成功");
        //$this->response(1, "解密失败");
    }

    public function commBestRank($uid,$dbname,$score,$field,$param,$order,$limit=200) {

        $where['status'] = 2;  // 授权用户
        $where[$param] = array('neq',0);

        $fields = !empty($field) ? $field : 'id,nickname,avatar,score';
        $orders = !empty($order) ? $order : 'score desc';

        $ret = M($dbname)->field($fields)->where($where)->order($orders)->limit($limit)->select();

        $rankNum = 0; // 排名
        if(!empty($ret)) {

            foreach($ret as $k=>$v) {

                if( $uid == $v['id'] && $score >= $v[$param] ) {
                    $rankNum = $k + 1;
                    break;
                }

                if( $score > $v[$param] ) {
                    $rankNum = $k + 1;
                    break;
                }
            }
        }

        if( $rankNum == 0 ) {

            $rankNum = 0;
        }

        return $rankNum;
    }

    //  掘金小美女 授权登录
    public function commLogin($dbname,$data,$cacheKey,$cacheval,$dbId=0) {

        if(empty($data)) { return false;}
        $openId = isset($data['openid']) ? $data['openid'] : '';
        $nickname = isset($data['nickname']) ? $data['nickname'] : '';
        $avatar = isset($data['avatar']) ? $data['avatar'] : '';
        $id = isset($data['id']) ? $data['id'] : '';

        $dataArr = array(
            'openid'=> $openId,
            'nickname'=> $nickname,
            'avatar'=> $avatar,
        );

        if(!empty($openId)) {
            $map['openid'] = $openId;
        }else {
            $map['id'] = $id;
        }

        $users = M($dbname)->where($map)->find();

        if(empty($users)){
            $dataArr['create_time'] = time();
            $dataArr['type'] = 1;   //新用户
            $ret = M($dbname)->add($dataArr);
            // 更改则更新用户信息
        }else {
            if($users['status']!=2) {  // 未授权取值
                $dataArr['type'] = 2;   //老用户
                $dataArr['status'] = 2;   //老用户
                // 授权用户登录
                if(!empty($users['nickname']) && !empty($users['avatar'])){
                    $dataArr['types'] = 4;  //第二次
                }else{
                    $dataArr['types'] = 3;  //第一次
                }
                $incr = $this->countLog($cacheKey,$cacheval,$dbId);  // 记录授权游客用户
            }
            $dataArr['update_time'] = date('Y-m-d H:i:s');
            $ret = M($dbname)->where($map)->save($dataArr);
        }

        if($ret) {
            $users = M($dbname)->where($map)->find();
            $users['incr'] = $incr;
            //$this->loginLog($users['id']);
        }

        return $users;
    }

    //  掘金小美女 未授权登录
    public function commLoginNotAuth($gameType,$dbname,$code,$cacheKey,$cacheval,$dbId=0,$sid=0,$z_index=0) {

        if(!$code) {
            $this->response(1,'code不能为空',"ERROR");
        }

        $info = $this->wxAuthor($gameType,$code);

        if(!empty($info['openid'])) {
            $content['openid'] = $info['openid'];
        }else{
            $this->response(1,'openid为空');
        }

        $userInfo = M($dbname)->where($content)->find();
        //状态 未授权首次:1,未授权第二次:2;授权首次:3，授权第二次:4
        if(empty($userInfo)) {
            $data['openid'] = $info['openid'];
            $data['source'] = !empty($sid) ? $sid : 0;
            $data['z_index'] = !empty($z_index) ? 2 : 0;
            $data['type'] = 1;//新用户
            $data['types'] = 1;//新用户
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret = M($dbname)->add($data);
            if(empty($ret)) {
                $this->response(1,'操作失败');
            }
            $incr = $this->countLog($cacheKey,$cacheval,$dbId);  // 记录未授权游客用户

            $map['id'] = $ret;
            $userInfo = M($dbname)->where($map)->find();
            $userInfo['session_key'] = $info['session_key'];
        }else{
            if($userInfo['types'] != 4){
                if($userInfo['status']==1){
                    //未授权第二次登录
                    if($userInfo['types']==1){
                        $data['types'] = 2;
                    }
                    // 维护久数据
                    if(!empty($userInfo['nickname']) && !empty($userInfo['avatar'])){
                        $data['status'] = 2;
                        $data['types'] = 4;
                    }
                }else{
                    // 授权登录
                    if(!empty($userInfo['nickname']) && !empty($userInfo['avatar'])){
                        $data['types'] = 4;
                    }else{
                        $data['types'] = 3;
                    }
                }
                $data['type'] = 2;  //老用户
                $data['update_time'] = date('Y-m-d H:i:s');
                $ret = M($dbname)->where($content)->save($data);
                if(empty($ret)) {
                    $this->response(1,'操作失败');
                }
            }else{
                $data['update_time'] = date('Y-m-d H:i:s');
                $ret = M($dbname)->where($content)->save($data);
            }

            $userInfo = M($dbname)->where($content)->find();
            $userInfo['session_key'] = $info['session_key'];
        }

        $userInfo['session_id'] = $this->getSession($gameType.':uid',$userInfo['id']);  // 获取sessionID
        $userInfo['session_key'] = $info['session_key'];
        $userInfo['incr'] = $incr;
        return $userInfo;
    }

    // 炮王2 授权登录
    public function  commLogin_p2($dbname,$data,$cacheKey,$cacheval,$dbId=0) {

        if(empty($data)) { return false;}
        $openId = $data['openid'];
        $nickname = isset($data['nickname']) ? $data['nickname'] : '';
        $avatar = isset($data['avatar']) ? $data['avatar'] : '';
        $id = isset($data['id']) ? $data['id'] : '';

        $dataArr = array(
            'userid'=> $openId,
            'nickname'=> $nickname,
            'avatar'=> $avatar,
            'status'=> 2,
        );

        $map['userid'] = $openId;
        $users = M($dbname)->where($map)->find();

        if(empty($users)){
            $this->response(2,'客户不存在');
        }else {
            if($users['status']!=2) {  // 第一次授权登录
                //$incr = $this->countLog($cacheKey,$cacheval,$dbId);  // 记录授权游客用户
                // 授权用户登录
                if(!empty($users['nickname']) && !empty($users['avatar'])){
                    $dataArr['types'] = 4;  //第二次
                }else{
                    $dataArr['types'] = 3;  //第一次
                }

            }
        }
        $dataArr['update_time'] = date('Y-m-d H:i:s');
        $ret = M($dbname)->where($map)->save($dataArr);
        if($ret) {
            $users = M($dbname)->where($map)->find();
            //$users['incr'] = $incr;
            //$this->loginLog($users['id']);
        }

        return $users;
    }

    // 炮王2 未授权登录
    public function commLoginNotAuth_p2($gameType,$dbname,$code,$cacheKey,$cacheval,$dbId=0,$sid=0) {

        $info = $this->wxAuthor($gameType,$code);   // 获取微信授权
        $openid = $info['openid'];

        if(!empty($openid)) {
            $content['userid'] = $openid;
        }else{
            $this->response(2,'授权失败');
        }

        $userInfo = M($dbname)->where($content)->find(); // 数据库是否存在
        if(empty($userInfo)) {
            // 第一次未授权登录
            $data['gold'] = 1000;  //金币初始化
            $data['diamonds'] = 50; //钻石初始化
            $data['userid'] = $openid;
            $data['source'] = !empty($sid) ? $sid : 0;
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret = M($dbname)->add($data);
            if(empty($ret)) {
                $this->response(1,'操作失败');
            }
            $incr = $this->countLog($cacheKey,$cacheval,$dbId);  // 记录未授权游客用户

            $map['id'] = $ret;
            $userInfo = M($dbname)->where($map)->find();
            $userInfo['session_key'] = $info['session_key'];
            //$userRedis = $redis->hSet($gameType,$openid,serialize($userInfo));
        }else{
            // 第二次未授权登录
            if($userInfo['types'] != 4){
                if($userInfo['status']==1){
                    //未授权第二次登录
                    if($userInfo['types']==1){
                        $data['types'] = 2;
                    }
                    // 维护久数据
                    if(!empty($userInfo['nickname']) && !empty($userInfo['avatar'])){
                        $data['status'] = 2;
                        $data['types'] = 4;
                    }
                }else{
                    // 授权登录
                    if(!empty($userInfo['nickname']) && !empty($userInfo['avatar'])){
                        $data['status'] = 2;
                        $data['types'] = 4;
                    }else{
                        $data['types'] = 3;
                    }
                }
                if($data['types']){
                    $data['update_time'] = date('Y-m-d H:i:s');
                    $ret = M($dbname)->where($content)->save($data);
                    if(empty($ret)) {
                        $this->response(1,'操作失败');
                    }
                    $userInfo['types'] = $data['types'];
                    $userInfo['update_time'] = $data['update_time'];
                    //$redis->hSet($gameType,$openid,serialize($userInfo));
                }

            }else{
                // 完全授权老用户
                $data['update_time'] = date('Y-m-d H:i:s');
                if(empty($userInfo['nickname'])){
                    $data['nickname'] = $info['nickname'];
                    $userInfo['nickname'] = $info['nickname'];
                    $ret = M($dbname)->where($content)->save($data);
                    //$redis->hSet($gameType,$openid,serialize($userInfo));
                }
                if (empty($userInfo['avatar'])){
                    $data['avatar'] = $info['avatar'];
                    $userInfo['nickname'] = $info['nickname'];
                    $ret = M($dbname)->where($content)->save($data);
                    //$redis->hSet($gameType,$openid,serialize($userInfo));
                }
            }

            $userInfo = M($dbname)->where($content)->find();
            /*$userTemp = $redis->hGet($gameType,$openid);
            $userInfo = unserialize($userTemp);*/
            $userInfo['session_key'] = $info['session_key'];
        }

        $userInfo['session_id'] = $this->getSession($gameType.':uid',$userInfo['id']);  // 获取sessionID
        $userInfo['session_key'] = $info['session_key'];
        $userInfo['incr'] = $incr;
        return $userInfo;
    }

    // 弓箭 授权登录
    public function commLogin_g($dbname,$data,$cacheKey,$cacheval,$dbId=0) {

        if(empty($data)) { return false;}
        $openId = isset($data['openid']) ? $data['openid'] : '';
        $nickname = isset($data['nickname']) ? $data['nickname'] : '';
        $avatar = isset($data['avatar']) ? $data['avatar'] : '';
        $id = isset($data['id']) ? $data['id'] : '';

        $dataArr = array(
            'openid'=> $openId,
            'nickname'=> $nickname,
            'avatar'=> $avatar,
            'status'=> 2,// 授权标识
        );
        if(!empty($openId)) {
            $map['openid'] = $openId;
        }else {
            $map['id'] = $id;
        }

        $users = M($dbname)->where($map)->find();

        if(empty($users)){
            // 第一次授权登录
            $dataArr['create_time'] = time();
            $dataArr['types'] = 3;   //新用户
            $ret = M($dbname)->add($dataArr);
            $users = M($dbname)->where($ret)->find();
            // 更改则更新用户信息
        }else {
            if($users['status']!=2) {  // 未授权而且openid 存在
                // 授权用户登录
                if(!empty($users['nickname']) && !empty($users['avatar'])){
                    $dataArr['types'] = 4;  //第二次
                }else{
                    $dataArr['types'] = 3;  //第一次
                }
                $incr = $this->countLog($cacheKey,$cacheval,$dbId);  // 记录授权游客用户

                $dataArr['update_time'] = date('Y-m-d H:i:s');
                $ret = M($dbname)->where($map)->save($dataArr);
                if(empty($ret)) {
                    $this->response(1,'操作失败');
                }
            }
            $users = M($dbname)->where($map)->find();
            $users['incr'] = $incr;
            //$this->loginLog($users['id']);
        }

        return $users;
    }

    // 弓箭 未授权登录
    public function commLoginNotAuth_g($gameType,$dbname,$code,$bs_code) {

        if(!$code) {
            $this->response(1,'code不能为空');
        }

        if(!empty($bs_code)){
            $info = array('openid'=>$code,'session_key'=>$code);
        }else{
            $info = $this->wxAuthor($gameType,$code);
        }

        if(!empty($info['openid'])) {
            $content['openid'] = $info['openid'];
        }

        $userInfo = M($dbname)->where($content)->find();

        // 游客登录
        if(empty($userInfo)) {
            // openid 为空 第一次登录
            $data['openid'] = $info['openid'];
            $data['source'] = !empty($sid) ? $sid : 0;
            $data['z_index'] = !empty($z_index) ? 2 : 0;
            $data['types'] = 1;//新用户
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret = M($dbname)->add($data);
            // 记录游客登录
            $temp['type'] = 1;
            $temp['create_time'] = date('Y-m-d H:i:s');
            $res = M('total_log')->add($temp);
            if(empty($ret)) {
                $this->response(1,'操作失败');
            }
            //$incr = $this->countLog($cacheKey,$cacheval,$dbId);  // 记录未授权游客用户

            $map['id'] = $ret;
            $userInfo = M($dbname)->where($map)->find();
            $userInfo['session_key'] = $info['session_key'];
        }else{
            if($userInfo['types'] != 4){
                if($userInfo['status']==1){
                    //未授权第二次登录
                    if($userInfo['types']==1){
                        $data['types'] = 2;
                    }
                    // 维护久数据
                    if(!empty($userInfo['nickname']) && !empty($userInfo['avatar'])){
                        $data['status'] = 2;
                        $data['types'] = 4;
                    }
                }else{
                    // 授权登录
                    if(!empty($userInfo['nickname']) && !empty($userInfo['avatar'])){
                        $data['types'] = 4;
                    }else{
                        $data['types'] = 3;
                    }
                }
                if($data['types']){
                    $data['update_time'] = date('Y-m-d H:i:s');
                    $ret = M($dbname)->where($content)->save($data);
                    if(empty($ret)) {
                        $this->response(1,'操作失败');
                    }
                }

            }else{
                $data['update_time'] = date('Y-m-d H:i:s');
                $ret = M($dbname)->where($content)->save($data);
            }
            $userInfo = M($dbname)->where($content)->find();
            $userInfo['session_key'] = $info['session_key'];

        }

        $userInfo['session_id'] = $this->getSession($gameType.':uid',$userInfo['id']);  // 获取sessionID
        $userInfo['session_key'] = $info['session_key'];
        //$userInfo['incr'] = $incr;
        return $userInfo;
    }

    //  泡泡龙 授权登录
    public function commLogin_ppl($dbname,$data,$cacheKey,$cacheval,$dbId=0) {

        if(empty($data)) { return false;}
        $openId = isset($data['openid']) ? $data['openid'] : '';
        $nickname = isset($data['nickname']) ? $data['nickname'] : '';
        $avatar = isset($data['avatar']) ? $data['avatar'] : '';
        $id = isset($data['id']) ? $data['id'] : '';

        $dataArr = array(
            'openid'=> $openId,
            'nickname'=> $nickname,
            'avatar'=> $avatar,
            'status'=> 2,
            'type'=>2   //老用户
        );

        if(!empty($openId)) {
            $map['openid'] = $openId;
        }else {
            $map['id'] = $id;
        }

        $users = M($dbname)->where($map)->find();

        if(empty($users)){
            $dataArr['create_time'] = time();
            $dataArr['type'] = 1;   //新用户
            $ret = M($dbname)->add($dataArr);
            $users = M($dbname)->where($map)->find();
            // 更改则更新用户信息
        }else {
            if($users['types']!=4){
                if($users['status']!=2) {  // 未授权取值
                    // 授权用户登录
                    if(!empty($users['nickname']) && !empty($users['avatar'])){
                        $dataArr['types'] = 4;  //第二次
                    }else{
                        $dataArr['types'] = 3;  //第一次
                    }
                    $incr = $this->countLog($cacheKey,$cacheval,$dbId);  // 记录授权游客用户
                }
                $dataArr['update_time'] = date('Y-m-d H:i:s');
                $ret = M($dbname)->where($map)->save($dataArr);
                if(empty($ret)) {
                    $this->response(1,'操作失败');
                }
            }
            $users = M($dbname)->where($map)->find();
        }


        $users['incr'] = $incr;
        //$this->loginLog($users['id']);

        return $users;
    }

    //  泡泡龙 未授权登录
    public function commLoginNotAuth_ppl($gameType,$dbname,$code,$cacheKey,$cacheval,$dbId=0,$sid=0,$z_index=0) {

        if(!$code) {
            $this->response(1,'code不能为空',"ERROR");
        }

        $info = $this->wxAuthor($gameType,$code);

        if(!empty($info['openid'])) {
            $content['openid'] = $info['openid'];
        }else{
            $this->response(1,'openid为空');
        }

        $userInfo = M($dbname)->where($content)->find();
        //状态 未授权首次:1,未授权第二次:2;授权首次:3，授权第二次:4
        if(empty($userInfo)) {
            $data['openid'] = $info['openid'];
            $data['source'] = !empty($sid) ? $sid : 0;
            $data['z_index'] = !empty($z_index) ? 2 : 0;
            $data['type'] = 1;//新用户
            $data['types'] = 1;//新用户
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret = M($dbname)->add($data);
            if(empty($ret)) {
                $this->response(1,'操作失败');
            }
            $incr = $this->countLog($cacheKey,$cacheval,$dbId);  // 记录未授权游客用户

            $map['id'] = $ret;
            $userInfo = M($dbname)->where($map)->find();
            $userInfo['session_key'] = $info['session_key'];
        }else{
            if($userInfo['types']!=4){  // 不是完全体
                if($userInfo['status']==1){
                    //未授权第二次登录
                    if($userInfo['types']==1){
                        $data['types'] = 2;
                    }
                    // 维护久数据
                    if(!empty($userInfo['nickname']) && !empty($userInfo['avatar'])){
                        $data['status'] = 2;
                        $data['types'] = 4;
                    }
                }else{
                    // 授权登录
                    if(!empty($userInfo['nickname']) && !empty($userInfo['avatar'])){
                        $data['types'] = 4;
                    }else{
                        $data['types'] = 3;
                    }
                }
                if($data['types']){
                    $data['type'] = 2;  //老用户
                    $data['update_time'] = date('Y-m-d H:i:s');
                    $ret = M($dbname)->where($content)->save($data);
                    if(empty($ret)) {
                        $this->response(1,'操作失败');
                    }
                }

            }else{
                $data['update_time'] = date('Y-m-d H:i:s');
                $ret = M($dbname)->where($content)->save($data);
            }

            $userInfo = M($dbname)->where($content)->find();
        }

        $userInfo['session_id'] = $this->getSession($gameType.':uid',$userInfo['id']);  // 获取sessionID
        $userInfo['session_key'] = $info['session_key'];
        $userInfo['incr'] = $incr;
        return $userInfo;
    }


    public function commLoginNotAuth_pplx($gameType,$dbname,$code,$cacheKey,$cacheval,$dbId=0,$sid=0,$z_index=0,$openid) {

        $content['openid'] = $openid;

        $userInfo = M($dbname)->where($content)->find();
        //状态 未授权首次:1,未授权第二次:2;授权首次:3，授权第二次:4
        if(empty($userInfo)) {
            $data['openid'] = $openid;
            $data['source'] = !empty($sid) ? $sid : 0;
            $data['z_index'] = !empty($z_index) ? 2 : 0;
            $data['type'] = 1;//新用户
            $data['types'] = 1;//新用户
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret = M($dbname)->add($data);
            if(empty($ret)) {
                $this->response(1,'操作失败');
            }
            $incr = $this->countLog($cacheKey,$cacheval,$dbId);  // 记录未授权游客用户

            $map['id'] = $ret;
            $userInfo = M($dbname)->where($map)->find();
        }else{
            if($userInfo['types']!=4){  // 不是完全体
                if($userInfo['status']!=2){
                    //未授权第二次登录
                    if($userInfo['types']!=2){
                        $data['types'] = 2;
                    }
                }else{
                    // 授权登录
                    if(!empty($userInfo['nickname']) && !empty($userInfo['avatar'])){
                        $data['types'] = 4;
                    }else{
                        $data['types'] = 3;
                    }

                }
                if($data['types']){
                    $data['type'] = 2;  //老用户
                    $data['update_time'] = date('Y-m-d H:i:s');
                    $ret = M($dbname)->where($content)->save($data);
                    if(empty($ret)) {
                        $this->response(1,'操作失败');
                    }
                }

            }

            $userInfo = M($dbname)->where($content)->find();
        }

        $userInfo['session_id'] = $this->getSession($gameType.':uid',$userInfo['id']);  // 获取sessionID
        $userInfo['incr'] = $incr;
        return $userInfo;
    }

    // 排行榜存
    public function setRankList($hash_key,$select,$value,$userid,$orderKey,$orderVal)
    {
        $redis = REDIS('activity');
        if( empty($userid) ) return false;
        $status = $this->getRankList($hash_key,false,$select,$orderKey,$userid,$orderVal);
        if($status) {
            $flag = $redis->hSet($hash_key, $userid, json_encode($value));
        }
        return $flag;

    }//End of function

    // 获取microtime
    public function get_microtime(){
        list($usec, $sec) = explode(' ', microtime());
        return (float)$usec + (float)$sec;
    }

    // 排行榜公共接口 —redis
    public function getRankList($hash_key,$return= false,$select=0,$param='',$userid='',$option='', $rankNumber=200, $orderNumber=false)
    {
        // 记录开始时间
        //$starttime = microtime(true);
        $redis = REDIS('activity');
        $redis->select($select);
        $cache_rank = $redis->hGetAll($hash_key);

        //  if(empty($cache_rank) ||!is_array($cache_rank)) return false;
        foreach ($cache_rank as $key=>$val){
            $val = json_decode($val , true);
            $cache_rank[$key] = $val;
            $power[$key]    = $val[$param];
        }
        // 先对$power排序，在对$cache_rank排序
        !$orderNumber && array_multisort($power, SORT_DESC, $cache_rank);
        $cache_rank_num = count($cache_rank);

        if( $cache_rank_num <= $rankNumber) {

            $pop_unit = end($cache_rank);

            if($option > $pop_unit[$param]) {  // 如果大于最后一名处理

                $info = $redis->hget($hash_key,$userid);

                if(!empty($info)) {
                    $data = json_decode($info,true);
                    $data[$param] = $option;
                    $flag = $redis->hSet($hash_key, $userid, json_encode($data));
                }else {
                    if( $cache_rank_num >= 200) {
                        $redis->hDel($hash_key,$pop_unit['id']);
                    }
                    return true;
                }
            }
        }
        if($return) {
            // 记录结束时间  输出运行时间
            /*$endtime = microtime(true);
            $times = round($endtime-$starttime,3).'秒';
            log::write("排行榜读取用时：".$times);
            log::write("消耗内存：".memory_get_usage());*/
            return $cache_rank;
        }else {
            return false;
        }

    }//End of function

    // 群分享记录公共接口
    public function getCryptData($uid,$gameType,$type=1,$cacheKey,$sessionKey,$encryptedData,$iv,$cacheKey2,$cacheval)
    {
        $data_type = C($gameType);  // 配置游戏类型
        $appid = $data_type['APPID'];

        //$encryptedData - 微信加密数据,$iv - 微信iv数据
        $pc = new \Org\Util\WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);

        $data = $data ? json_decode($data, true) : '';
        $openGId = isset($data['openGId']) ? $data['openGId'] : 0;

        $redis = REDIS('activity');
        $redis->select(5);
        $evening = date('Y-m-d 23:59:59'); //每日23点59分
        // $uid - 用户id,$type - 分享类型(1普通分享，2分享复活),$cacheKey - 分享缓存键
        $userKey = sprintf($cacheKey,$uid,$type,$openGId);  //用户主键分享到群
        $shareKey = $redis->get($userKey);
        if( $type == 2 && $shareKey == 1  ) {
            $this->response(2,'每局游戏同一群只能分享一次');
        }

        if( $type == 1 && $shareKey == 1  ) {
            $this->response(3,'每天同一群只能分享一次');
        }

        if ( $errCode == 0 ) {  // 解密成功

            $redis->set($userKey,1);  // 标记
            $redis->exprieAt($userKey,strtotime(date('Y-m-d 23:59:59'))); // 每日23点59分过期
            // 群分享记录
            $groups = array(
                'userid' => $uid,
                'gid' => $openGId,
                'type'=> $type,
                'create_time'=>date('Y-m-d H:i:s')
            );
            $ret = M('share_group_log')->add($groups);

            $this->countLog($cacheKey2,$cacheval,1);  // 记录分享次数日志 键域
            $result = $data ? json_decode($data, true) : '';
            $this->response(0, "成功解密",$result);
        }

        $this->response(0, "解密成功");
        //$this->response(1, "解密失败");
    }

    public function getChannelCount($countKey,$sid,$typeName,$incr,$dbid=0) {
        $redis = REDIS('activity');
        $redis->select($dbid);
        $list = $redis->hget($countKey,$sid);
        $data = json_decode($list,true);
        if(!empty($incr)) {
            $data[$typeName] = $incr;
        }
        $redis->hset($countKey,$sid,json_encode($data));
        return true;
    }


    public function response($ret = 0, $msg = '', $data = array(), $num = '') {
        $json = array('ret' => $ret, 'msg' => $msg);
        if(!empty($data)) {
            $json['data'] = $data;
        }
        if(!empty($num)) {
            $json['number'] = $num;
        }
        $this->ajaxReturn($json);
    }

    function convert($size){
        $unit=array('b','kb','mb','gb','tb','pb');
        return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
    }

    // 公共转发记录接口
    public function getForward($uid,$invite_uid,$type_table,$type){
        if(empty($uid) || empty($type)){
            $this->response(1, "id和类型不能为空");
        }
        $redis = REDIS('activity');
        $redis->select(6);
        if($type==1){ //查询
            $res = $redis->hGet($type_table,'forward:'.$uid); // 缓存key 字段
            if($res){
                $this->response(0, "ok",$res);
            }else{
                $this->response(1, "该用户没有邀请数据");
            }
        }elseif ($type==2){ //添加
            $i_uid = $redis->hGet($type_table.'s',$uid.'-'.$invite_uid);
            if(empty($i_uid)){
                $type_tables =$redis->hSet($type_table.'s',$uid.'-'.$invite_uid,1);   // 记录邀请与被邀请关联
                $res = $this->countLog($type_table,'forward:'.$uid,6);  // 转发的次数+1
                if($res){
                    $this->response(0, "添加成功");
                }else{
                    $this->response(1, "添加失败");
                }
            }else{
                $this->response(1, "已经邀请过");
            }
        }elseif ($type==3){ //删除
            $res = $redis->hDel($type_table,'forward:'.$uid);
            if($res){
                $this->response(0, "删除成功");
            }else{
                $this->response(1, "删除失败");
            }
        }else{
            $this->response(3, "类型不存在");
        }

    }

}